package com.bruce.asurada.sso.service.impl;

import com.bruce.asurada.sso.service.PhoneCodeService;
import com.bruce.asurada.sso.service.SmsService;
import com.bruce.asurada.sso.util.RedisUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class PhoneCodeServiceImpl implements PhoneCodeService {
    @Autowired
    private SmsService smsService;
    
    @Autowired
    private RedisUtil redisUtil;
    
    // 验证码有效期：5分钟
    private static final int CODE_EXPIRE_MINUTES = 5;
    // 同一手机号发送间隔：60秒
    private static final int SEND_INTERVAL_SECONDS = 60;
    // 每天最大发送次数
    private static final int MAX_DAILY_SEND_COUNT = 10;
    
    @Override
    public boolean generateAndSendCode(String phone) throws Exception{
        if (!isValidPhone(phone)) {
            return false;
        }
        
        // 检查发送频率
        String intervalKey = "phone_code_interval:" + phone;
        if (redisUtil.hasKey(intervalKey)) {
            return false;
        }
        
        // 检查每日发送次数
        String countKey = "phone_code_daily_count:" + phone + ":" + LocalDateTime.now().toLocalDate();
        String countStr = (String) redisUtil.get(countKey);
        int count = StringUtils.hasText(countStr) ? Integer.parseInt(countStr) : 0;
        if (count >= MAX_DAILY_SEND_COUNT) {
            return false;
        }
        
        // 生成6位验证码
        String code = generateCode();
        
        // 发送短信
        boolean sendSuccess = smsService.sendVerificationCode(phone, code);
        if (!sendSuccess) {
            return false;
        }
        
        // 存储验证码到Redis
        String codeKey = "phone_code:" + phone;
        redisUtil.set(codeKey, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
        
        // 设置发送间隔
        redisUtil.set(intervalKey, "1", SEND_INTERVAL_SECONDS, TimeUnit.SECONDS);
        
        // 增加发送次数
        redisUtil.set(countKey, String.valueOf(count + 1), 24, TimeUnit.HOURS);
        
        return true;
    }
    
    @Override
    public boolean verifyCode(String phone, String code)throws Exception {
        if (!isValidPhone(phone) || !isValidCode(code)) {
            return false;
        }
        
        String codeKey = "phone_code:" + phone;
        String storedCode = (String) redisUtil.get(codeKey);
        
        if (code.equals(storedCode)) {
            // 验证成功后删除验证码，防止重复使用
            redisUtil.delete(codeKey);
            return true;
        }
        
        return false;
    }
    
    // 生成6位数字验证码
    private String generateCode() {
        Random random = new Random();
        int codeNum = 100000 + random.nextInt(900000);
        return String.valueOf(codeNum);
    }
    
    // 简单验证手机号格式
    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }
    
    // 验证验证码格式
    private boolean isValidCode(String code) {
        return code != null && code.matches("^\\d{6}$");
    }
}
